package crp.services.api.graphql;


import com.qwlabs.graphql.relay.Connection;
import com.qwlabs.graphql.relay.Relays;
import crp.core.department.app.DepartmentService;
import crp.core.department.domain.models.DepartmentEntity;
import crp.services.api.graphql.models.CreateDepartmentInput;
import crp.services.api.graphql.models.DepartmentPayload;
import org.eclipse.microprofile.graphql.DefaultValue;
import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Mutation;
import org.eclipse.microprofile.graphql.Query;

import javax.annotation.security.PermitAll;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@GraphQLApi
@RequestScoped
@Transactional
public class DepartmentGraphQLApi {
    private final DepartmentService departmentService;

    @Inject
    public DepartmentGraphQLApi(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    @Query
    @PermitAll
    @NotNull
    public Connection<DepartmentPayload> departments(
            @DefaultValue("0") String after,
            @DefaultValue("10") Integer first) {
        return Relays.of(departmentService.searcher().by(Relays.of(after, first)), DepartmentPayload::of);
    }

    @Mutation
    @PermitAll
    @NotNull
    public DepartmentPayload createDepartment(@Valid CreateDepartmentInput input) {
        DepartmentEntity department = departmentService.creator()
                .upsert(input.getCode(), input.getName());
        return DepartmentPayload.of(department);
    }
}
